import React, { useState, useEffect } from 'react'
import styles from '../../styles/login/Login.scss'
import { Button } from 'antd'
import LoginInput from './LoginInput'
import VerifyInput from './VerifyInput'
import axios from 'axios'
import { backIP, axiosConfig, success, error, warning } from '../common/config'
import IdentifySelect from './IdentifySelect'
import Router from 'next/router'
import cookie from 'react-cookies'
import { getToken } from '../common/util'
import store from '../redux/store'
import { userDataConfig } from '../common/Header'
import ShowLoginedUser from './ShowLoginedUser'

const words: string[] = ['登录', '注册']

// 登录注册的数据类型
export interface settingConfig {
    icon: string,
    isPassword: boolean,
    changeLoginData?: changeInputDataConfig,
    type: string,
    placeholder?: string
}

// 改变输入的值的函数接口
export interface changeInputDataConfig {
    (data: string, type: string): void;
}

// 两个输入框的样式数据
const loginInputSettings: settingConfig[] = [
    {
        icon: 'iconziyuanxhdpi',
        isPassword: false,
        type: 'number',
        placeholder: '学号'
    },
    {
        icon: 'iconmima',
        isPassword: true,
        type: 'password',
        placeholder: '密码'
    }
]

// 两个输入框的样式数据
const enrollInputSettings: settingConfig[] = [
    {
        icon: 'iconziyuanxhdpi',
        isPassword: false,
        type: 'number',
        placeholder: '学号'
    },
    {
        icon: 'iconmima',
        isPassword: true,
        type: 'password',
        placeholder: '密码'
    },
    {
        icon: 'iconzuoxixingming',
        isPassword: false,
        type: 'real_name',
        placeholder: '真实姓名'
    }
]

function Login() {
    /* 1代表登录，2代表注册 */
    const [activeID, setActiveID] = useState(1);
    const [userData, setUserData] = useState<userDataConfig>({})
    const [logined, setLogined] = useState(false)
    const [loginData, setLoginData] = useState({
        number: '',
        password: '',
        verifyCode: ''
    });
    const [enrollData, setEnrollData] = useState({
        number: '',
        password: '',
        real_name: '',
        identify: '学生'
    });

    const saveUserDataInStore = async (token: string) => {
        const { data: res }: { data: axiosConfig } = await axios.get(`${backIP}/user`, {
            headers: {
                Authorization: token
            }
        })
        if (res.code === 0) {
            setUserData(res.data)
            setLogined(true)
        }
    }
    const changeLoginData: changeInputDataConfig = (data, type) => {
        setLoginData({
            ...loginData,
            [type]: data
        })
    }

    const changeEnrollData: changeInputDataConfig = (data, type) => {
        setEnrollData({
            ...enrollData,
            [type]: data
        })
    }

    const handleSubmit = async () => {
        const data = activeID === 1 ? loginData : enrollData;
        console.log(data)
        if (activeID === 1) {
            const { data: res }: { data: axiosConfig } = await axios.put(`${backIP}/login`, data, {withCredentials: true})
            cookie.save('Authorization', res.data)
            handleMessage(res.code, res.message)
        }

        if (activeID === 2) {
            const { data: res }: { data: axiosConfig } = await axios.put(`${backIP}/enroll`, data)
            handleMessage(res.code, res.message)
        }
    }

    const handleMessage = (code: number, message: string) => {
        if (code === 0) {
            success(message)
            Router.push('/home')
        } else {
            error(message)
        }
    }
    const judgeLoginedStatus = () => {
        const token: string = getToken();
        if (token) {
            // 说明为空对象，则向后端请求数据，如果不是空对象，则显示用户框
            if (JSON.stringify(store.getState()) === "{}") {
                saveUserDataInStore(token)
            } else {
                setLogined(true)
                setUserData(store.getState())
            }
        } else {
            setLogined(false)
        }
    }
    const switchLoginWay = () => {
        const token: string = getToken();
        if (!token) {
            warning('无已有账号，请进行第一次登录后，系统会自动创建已有账号进行登录')
            return
        }
        judgeLoginedStatus()
    }

    useEffect(() => {
        judgeLoginedStatus()
    }, [])

    return (
        <div className={styles.layout}>
            <div className={styles.main}>
                <p className={styles.loginTitle}>教室管理信息系统</p>
                <div className={styles.title}>
                    {
                        words.map((word, index) => {
                            return <div key={index}>
                                <p
                                    className={styles.word}
                                    style={{
                                        color: (index + 1 === activeID ? '#000' : '#ccc')
                                    }}
                                    onClick={() => { setActiveID(index + 1) }}
                                >
                                    {word}
                                </p>
                            </div>
                        })
                    }
                    <p
                        className={styles.line}
                        style={{
                            left: (activeID === 1 ? 0 : 320)
                        }}
                    ></p>
                </div>
                <section className={styles.inputSection}>
                    <div className={styles.tabSection} style={{
                        transform: `translateX(${-400 * (activeID - 1)}px)`
                    }}>
                        {
                            logined ? <ShowLoginedUser userData={userData} /> : <>
                                {
                                    loginInputSettings.map((item, index) => {
                                        return <LoginInput
                                            icon={item.icon}
                                            key={index}
                                            type={item.type}
                                            isPassword={item.isPassword}
                                            callback={changeLoginData}
                                            placeholder={item.placeholder}
                                        />
                                    })
                                }
                                <VerifyInput type='verifyCode' callback={changeLoginData} />
                                <div className={styles.otherOperation}>
                                    <p className={styles.operation}>忘记密码</p>
                                    <p className={styles.operation} onClick={switchLoginWay}>使用已有账号进行登录</p>
                                </div>
                            </>
                        }
                    </div>
                    <div className={styles.tabSection} style={{
                        transform: `translateX(${-400 * (activeID - 1)}px)`
                    }}>
                        {
                            enrollInputSettings.map((item, index) => {
                                return <LoginInput
                                    icon={item.icon}
                                    key={index}
                                    type={item.type}
                                    isPassword={item.isPassword}
                                    callback={changeEnrollData}
                                    placeholder={item.placeholder}
                                />
                            })
                        }
                        <IdentifySelect type='identify' callback={changeEnrollData} />
                    </div>
                </section>
                {
                    logined ? <p className={styles.switchLoginWay} onClick={() => { setLogined(false) }}>使用其他账号登录</p> :
                        <Button
                            type="primary"
                            className={styles.btn}
                            onClick={handleSubmit}
                        >
                            {words[activeID - 1]}
                        </Button>
                }
            </div>
        </div>
    )
}

export default Login